<?php
namespace app\controller;

use think\Request;
use think\Response;
use think\facade\Db;

class ApprovalFlow
{
    /**
     * 获取审批流程列表
     */
    public function getList()
    {
        $page = input('pageNo', 1);
        $pageSize = input('pageSize', 20);
        
        $list = Db::name('approval_flow')
            ->order('sort desc, id desc')
            ->page($page, $pageSize)
            ->select();
            
        $total = Db::name('approval_flow')->count();
        
        return json(['code' => 200, 'msg' => 'success', 'data' => [
            'list' => $list,
            'total' => $total
        ]]);
    }

    /**
     * 创建审批流程
     */
    public function create()
    {
        $data = input('post.');
        
        Db::startTrans();
        try {
            // 保存主表数据
            $flowId = Db::name('approval_flow')->insertGetId([
                'title' => $data['title'],
                'icon' => $data['icon'],
                'description' => $data['description'],
                'sort' => $data['sort'] ?? 0,
                'is_leave_type' => $data['is_leave_type'] ?? 0,
                'status' => 1
            ]);
            
            // 保存字段数据
            if (!empty($data['fields'])) {
                $fields = [];
                foreach ($data['fields'] as $index => $field) {
                    $fields[] = [
                        'flow_id' => $flowId,
                        'field_id' => $field['field_id'],
                        'field_name' => $field['field_name'],
                        'field_type' => $field['field_type'],
                        'field_options' => isset($field['field_options']) ? json_encode($field['field_options']) : null,
                        'is_required' => $field['is_required'] ? 1 : 2,
                        'sort' => $index
                    ];
                }
                Db::name('approval_flow_field')->insertAll($fields);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '创建成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取审批流程详情
     */
    public function detail($id)
    {
        $flow = Db::name('approval_flow')->where('id', $id)->find();
        if (!$flow) {
            return json(['code' => 404, 'msg' => '审批流程不存在']);
        }
        
        $fields = Db::name('approval_flow_field')
            ->where('flow_id', $id)
            ->order('sort asc')
            ->select()->toArray();
            
        // 处理字段选项
        foreach ($fields as &$field) {
            if ($field['field_options']) {
                // 解码JSON选项
                $options = json_decode($field['field_options'], true);
                // 确保解码成功
                if (is_array($options)) {
                    $field['field_options'] = $options;
                } else {
                    // 如果解码失败，提供一个空数组
                    $field['field_options'] = [];
                }
            }
        }
        
        $flow['fields'] = $fields;
        return json(['code' => 200, 'msg' => 'success', 'data' => $flow]);
    }

    /**
     * 更新审批流程
     */
    public function update($id)
    {
        $data = input('post.');
        
        Db::startTrans();
        try {
            // 更新主表
            Db::name('approval_flow')->where('id', $id)->update([
                'title' => $data['title'],
                'icon' => $data['icon'],
                'description' => $data['description'],
                'sort' => $data['sort'] ?? 0,
                'is_leave_type' => $data['is_leave_type'] ?? 0
            ]);
            
            // 删除原有字段
            Db::name('approval_flow_field')->where('flow_id', $id)->delete();
            
            // 重新保存字段
            if (!empty($data['fields'])) {
                $fields = [];
                foreach ($data['fields'] as $index => $field) {
                    $fields[] = [
                        'flow_id' => $id,
                        'field_id' => $field['field_id'],
                        'field_name' => $field['field_name'],
                        'field_type' => $field['field_type'],
                        'field_options' => isset($field['field_options']) ? json_encode($field['field_options']) : null,
                        'is_required' => $field['is_required'] ? 1 : 2,
                        'sort' => $index
                    ];
                }
                Db::name('approval_flow_field')->insertAll($fields);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除审批流程
     */
    public function delete()
    {
        $ids = input('ids');
        if (empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $ids = explode(',', $ids);
        Db::startTrans();
        try {
            Db::name('approval_flow')->whereIn('id', $ids)->delete();
            // 级联删除字段配置
            Db::name('approval_flow_field')->whereIn('flow_id', $ids)->delete();
            
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            // 检查是否是外键约束错误
            if (strpos($e->getMessage(), 'foreign key constraint fails') !== false) {
                return json(['code' => 500, 'msg' => '该审批流程已有关联数据，禁止删除。错误编码：00255']);
            }
            return json(['code' => 500, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新审批流程状态
     */
    public function updateStatus()
    {
        $id = input('id');
        $status = input('status');
        
        if (empty($id) || !isset($status)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            Db::name('approval_flow')->where('id', $id)->update(['status' => $status ? 1 : 2]);
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
}